import React, { createContext, useContext, ReactNode } from 'react';
import { Modal, Button, message } from 'antd';
import { ExclamationCircleOutlined, CheckCircleOutlined, InfoCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';

interface ConfirmOptions {
  title?: string;
  content?: string;
  okText?: string;
  cancelText?: string;
  type?: 'info' | 'success' | 'error' | 'warning' | 'confirm';
  icon?: React.ReactNode;
  onOk?: () => void | Promise<void>;
  onCancel?: () => void;
  okButtonProps?: any;
  cancelButtonProps?: any;
  centered?: boolean;
  maskClosable?: boolean;
  width?: number;
}

interface NotificationOptions {
  type: 'success' | 'error' | 'warning' | 'info';
  message: string;
  description?: string;
  duration?: number;
  placement?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight';
  onClick?: () => void;
  onClose?: () => void;
}

interface FeedbackContextType {
  confirm: (options: ConfirmOptions) => Promise<boolean>;
  alert: (message: string, type?: 'info' | 'success' | 'error' | 'warning') => void;
  notify: (options: NotificationOptions) => void;
  prompt: (title: string, defaultValue?: string) => Promise<string | null>;
}

const FeedbackContext = createContext<FeedbackContextType | undefined>(undefined);

export const useFeedback = () => {
  const context = useContext(FeedbackContext);
  if (!context) {
    throw new Error('useFeedback must be used within a FeedbackProvider');
  }
  return context;
};

interface FeedbackProviderProps {
  children: ReactNode;
}

export const FeedbackProvider: React.FC<FeedbackProviderProps> = ({ children }) => {
  const confirm = async (options: ConfirmOptions): Promise<boolean> => {
    return new Promise((resolve) => {
      const getIcon = () => {
        if (options.icon) return options.icon;
        switch (options.type) {
          case 'success':
            return <CheckCircleOutlined className="text-green-500" />;
          case 'error':
            return <ExclamationCircleOutlined className="text-red-500" />;
          case 'warning':
            return <ExclamationCircleOutlined className="text-orange-500" />;
          case 'info':
            return <InfoCircleOutlined className="text-blue-500" />;
          default:
            return <QuestionCircleOutlined className="text-gray-500" />;
        }
      };

      Modal.confirm({
        title: options.title || '确认操作',
        content: options.content,
        icon: getIcon(),
        okText: options.okText || '确定',
        cancelText: options.cancelText || '取消',
        centered: options.centered !== false,
        maskClosable: options.maskClosable !== false,
        width: options.width || 416,
        okButtonProps: {
          ...options.okButtonProps,
          type: options.type === 'error' ? 'primary' : 'primary'
        },
        cancelButtonProps: options.cancelButtonProps,
        onOk: async () => {
          try {
            if (options.onOk) {
              await options.onOk();
            }
            resolve(true);
          } catch (error) {
            console.error('Confirm onOk error:', error);
            resolve(false);
          }
        },
        onCancel: () => {
          if (options.onCancel) {
            options.onCancel();
          }
          resolve(false);
        }
      });
    });
  };

  const alert = (msg: string, type: 'info' | 'success' | 'error' | 'warning' = 'info') => {
    const getIcon = () => {
      switch (type) {
        case 'success':
          return <CheckCircleOutlined className="text-green-500" />;
        case 'error':
          return <ExclamationCircleOutlined className="text-red-500" />;
        case 'warning':
          return <ExclamationCircleOutlined className="text-orange-500" />;
        default:
          return <InfoCircleOutlined className="text-blue-500" />;
      }
    };

    Modal.info({
      title: '提示',
      content: msg,
      icon: getIcon(),
      okText: '知道了',
      centered: true
    });
  };

  const notify = (options: NotificationOptions) => {
    const { type, message: msg, description, duration = 4.5, placement = 'topRight' } = options;
    
    // 使用 Ant Design 的 message 组件
    switch (type) {
      case 'success':
        message.success({
          content: msg,
          duration,
          onClick: options.onClick
        });
        break;
      case 'error':
        message.error({
          content: msg,
          duration,
          onClick: options.onClick
        });
        break;
      case 'warning':
        message.warning({
          content: msg,
          duration,
          onClick: options.onClick
        });
        break;
      default:
        message.info({
          content: msg,
          duration,
          onClick: options.onClick
        });
    }
  };

  const prompt = async (title: string, defaultValue = ''): Promise<string | null> => {
    return new Promise((resolve) => {
      let inputValue = defaultValue;

      Modal.confirm({
        title,
        content: (
          <div className="mt-4">
            <input
              type="text"
              defaultValue={defaultValue}
              onChange={(e) => {
                inputValue = e.target.value;
              }}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              autoFocus
            />
          </div>
        ),
        okText: '确定',
        cancelText: '取消',
        centered: true,
        onOk: () => {
          resolve(inputValue);
        },
        onCancel: () => {
          resolve(null);
        }
      });
    });
  };

  const contextValue: FeedbackContextType = {
    confirm,
    alert,
    notify,
    prompt
  };

  return (
    <FeedbackContext.Provider value={contextValue}>
      {children}
    </FeedbackContext.Provider>
  );
};

// 便捷的操作确认 Hook
export const useConfirmAction = () => {
  const { confirm } = useFeedback();

  const confirmDelete = async (itemName?: string): Promise<boolean> => {
    return confirm({
      title: '确认删除',
      content: `确定要删除${itemName ? ` "${itemName}"` : '此项'}吗？此操作不可撤销。`,
      type: 'error',
      okText: '删除',
      cancelText: '取消',
      okButtonProps: { danger: true }
    });
  };

  const confirmSave = async (hasChanges = true): Promise<boolean> => {
    if (!hasChanges) return true;
    
    return confirm({
      title: '保存更改',
      content: '检测到未保存的更改，是否保存？',
      type: 'warning',
      okText: '保存',
      cancelText: '不保存'
    });
  };

  const confirmLeave = async (): Promise<boolean> => {
    return confirm({
      title: '确认离开',
      content: '您有未保存的更改，确定要离开此页面吗？',
      type: 'warning',
      okText: '离开',
      cancelText: '留在此页',
      okButtonProps: { danger: true }
    });
  };

  const confirmAction = async (action: string, description?: string): Promise<boolean> => {
    return confirm({
      title: `确认${action}`,
      content: description || `确定要${action}吗？`,
      type: 'confirm',
      okText: '确定',
      cancelText: '取消'
    });
  };

  return {
    confirmDelete,
    confirmSave,
    confirmLeave,
    confirmAction,
    confirm
  };
};

// 便捷的通知 Hook
export const useNotification = () => {
  const { notify, alert } = useFeedback();

  const success = (message: string, description?: string) => {
    notify({ type: 'success', message, description });
  };

  const error = (message: string, description?: string) => {
    notify({ type: 'error', message, description });
  };

  const warning = (message: string, description?: string) => {
    notify({ type: 'warning', message, description });
  };

  const info = (message: string, description?: string) => {
    notify({ type: 'info', message, description });
  };

  return {
    success,
    error,
    warning,
    info,
    alert,
    notify
  };
};

export default FeedbackProvider;